<?php

ob_implicit_flush();
// if (!extension_loaded('sockets')) {
//     die('The sockets extension is not loaded.');
// }
// 
$socket = new Socket();
$socket->accept();


class Socket
{
    protected $domain = AF_INET;
    protected $type = SOCK_STREAM;
    protected $protocol = SOL_TCP;
    protected $socket = null;
    public $addr = '127.0.0.1';
    public $port = 8080;


    public function __construct()
    {
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_bind($this->socket, $this->addr, $this->port);
        socket_listen($this->socket);

        $this->log("\n\nServer Started : ". date('Y-m-d H:i:s'));
        $this->log('Listening on   : '. $this->addr . ' port : ' . $this->port);
    }

    public function run()
    {
    }

    public function accept($value='')
    {
        while (true) {
            $current = socket_accept($this->socket);
            $buf = null;
            $buf = socket_read($current, 2048, PHP_BINARY_READ);

            $talkback = "OK\n";

            socket_write($current, $talkback, strlen($talkback));
                socket_close($current);
                break;
        }
    }

    public function __destruct()
    {
        socket_close($this->socket);
    }

    private function log($str = '')
    {
        echo $str;
        echo "\n";
    }
}
